#!/usr/bin/env python
"""
学生数据重置和初始化脚本
清理现有数据并创建新的测试数据
"""
import os
import sys
import django

# 设置Django环境
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'inter_api.settings')
django.setup()

from django.contrib.auth import get_user_model
from django.db import transaction
from students.models import School, Major, Grade, Student
from accounts.models import User

User = get_user_model()


def clear_all_data():
    """清理所有相关数据"""
    print("🗑️  开始清理现有数据...")
    
    with transaction.atomic():
        # 删除学生数据（会级联删除相关的用户）
        student_count = Student.objects.count()
        Student.objects.all().delete()
        print(f"   ✅ 删除了 {student_count} 个学生记录")
        
        # 删除学生角色的用户（如果有残留）
        student_users = User.objects.filter(role='student')
        student_user_count = student_users.count()
        student_users.delete()
        print(f"   ✅ 删除了 {student_user_count} 个学生用户账号")
        
        # 清理年级数据
        grade_count = Grade.objects.count()
        Grade.objects.all().delete()
        print(f"   ✅ 删除了 {grade_count} 个年级记录")
        
        # 清理专业数据
        major_count = Major.objects.count()
        Major.objects.all().delete()
        print(f"   ✅ 删除了 {major_count} 个专业记录")
        
        # 清理学校数据
        school_count = School.objects.count()
        School.objects.all().delete()
        print(f"   ✅ 删除了 {school_count} 个学校记录")
    
    print("✅ 数据清理完成！")


def create_basic_data():
    """创建基础数据（学校、专业、年级）"""
    print("🏗️  开始创建基础数据...")
    
    # 创建学校
    school = School.objects.create(
        name="鸥鹏科技大学",
        code="OPSTU",
        principal="张校长",
        phone="010-12345678",
        address="北京市海淀区中关村大街1号"
    )
    print(f"   ✅ 创建学校: {school.name}")
    
    # 创建专业
    majors_data = [
        {"name": "计算机科学与技术", "description": "培养计算机科学与技术专业人才"},
        {"name": "软件工程", "description": "培养软件工程专业人才"},
        {"name": "数据科学与大数据技术", "description": "培养大数据分析专业人才"},
        {"name": "人工智能", "description": "培养人工智能专业人才"},
        {"name": "网络工程", "description": "培养网络工程专业人才"},
    ]

    majors = []
    for major_data in majors_data:
        major = Major.objects.create(**major_data)
        majors.append(major)
        print(f"   ✅ 创建专业: {major.name}")
    
    # 创建年级
    grades_data = [
        {"name": "2021级", "description": "2021年入学"},
        {"name": "2022级", "description": "2022年入学"},
        {"name": "2023级", "description": "2023年入学"},
        {"name": "2024级", "description": "2024年入学"},
    ]

    grades = []
    for grade_data in grades_data:
        grade = Grade.objects.create(**grade_data)
        grades.append(grade)
        print(f"   ✅ 创建年级: {grade.name}")
    
    return grades


def create_test_students(grades):
    """创建测试学生数据"""
    print("👥 开始创建测试学生数据...")
    
    # 测试学生数据
    students_data = [
        {
            'student_id': 'CS2024001',
            'name': '张三',
            'username': 'zhangsan2024',
            'gender': 'M',
            'phone': '13800138001',
            'email': 'zhangsan@opstu.edu.cn',
            'grade': grades[3],  # 2024级
        },
        {
            'student_id': 'CS2024002',
            'name': '李四',
            'username': 'lisi2024',
            'gender': 'F',
            'phone': '13800138002',
            'email': 'lisi@opstu.edu.cn',
            'grade': grades[3],  # 2024级
        },
        {
            'student_id': 'SE2024001',
            'name': '王五',
            'username': 'wangwu2024',
            'gender': 'M',
            'phone': '13800138003',
            'email': 'wangwu@opstu.edu.cn',
            'grade': grades[3],  # 2024级
        },
        {
            'student_id': 'SE2024002',
            'name': '赵六',
            'username': 'zhaoliu2024',
            'gender': 'F',
            'phone': '13800138004',
            'email': 'zhaoliu@opstu.edu.cn',
            'grade': grades[3],  # 2024级
        },
        {
            'student_id': 'DS2023001',
            'name': '孙七',
            'username': 'sunqi2023',
            'gender': 'M',
            'phone': '13800138005',
            'email': 'sunqi@opstu.edu.cn',
            'grade': grades[2],  # 2023级
        },
        {
            'student_id': 'AI2023001',
            'name': '周八',
            'username': 'zhouba2023',
            'gender': 'F',
            'phone': '13800138006',
            'email': 'zhouba@opstu.edu.cn',
            'grade': grades[2],  # 2023级
        },
    ]
    
    created_students = []
    for student_data in students_data:
        try:
            with transaction.atomic():
                # 创建用户账号
                user = User.objects.create_user(
                    username=student_data['username'],
                    password='123456',  # 默认密码
                    email=student_data['email'],
                    phone=student_data['phone'],
                    first_name=student_data['name'],
                    role='student',
                    is_active=True
                )
                
                # 创建学生档案
                student = Student.objects.create(
                    user=user,
                    student_id=student_data['student_id'],
                    name=student_data['name'],
                    gender=student_data['gender'],
                    phone=student_data['phone'],
                    email=student_data['email'],
                    grade=student_data['grade'],
                    status='active',
                    employment_status='unemployed',
                    resume_status='not_started'
                )
                
                created_students.append(student)
                print(f"   ✅ 创建学生: {student.name} (学号: {student.student_id}, 用户名: {user.username})")
                
        except Exception as e:
            print(f"   ❌ 创建学生失败: {student_data['name']} - {str(e)}")
    
    return created_students


def main():
    """主函数"""
    print("🚀 开始重置学生数据...")
    print("=" * 50)
    
    try:
        # 1. 清理现有数据
        clear_all_data()
        print()
        
        # 2. 创建基础数据
        grades = create_basic_data()
        print()
        
        # 3. 创建测试学生
        students = create_test_students(grades)
        print()
        
        # 4. 显示结果
        print("🎉 数据重置完成！")
        print("=" * 50)
        print(f"📊 统计信息:")
        print(f"   学校数量: {School.objects.count()}")
        print(f"   专业数量: {Major.objects.count()}")
        print(f"   年级数量: {Grade.objects.count()}")
        print(f"   学生数量: {Student.objects.count()}")
        print(f"   学生用户数量: {User.objects.filter(role='student').count()}")
        print()
        
        print("🔑 测试登录信息:")
        for student in students:
            print(f"   学号: {student.student_id} | 用户名: {student.user.username} | 密码: 123456")
        print()
        
        print("💡 登录方式说明:")
        print("   学生可以使用以下任意一种方式登录:")
        print("   1. 学号 (如: CS2024001)")
        print("   2. 用户名 (如: zhangsan2024)")
        print("   3. 手机号 (如: 13800138001)")
        print("   4. 邮箱 (如: zhangsan@opstu.edu.cn)")
        
    except Exception as e:
        print(f"❌ 重置过程中出现错误: {str(e)}")
        sys.exit(1)


if __name__ == '__main__':
    main()
